package com.example.handlernetimage;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

import com.example.handlernetimage.NetThread.DataReceiver;

public class MainActivity extends Activity {
	
	String url = "http://img4q.duitang.com/uploads/item/201405/16/20140516000627_x5eeu.jpeg";
	private Button click;
	private ImageView show;
	private ProgressDialog dialog = null;  
	private static final int DOWNLOAD_IMG = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
		click.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				new NetThread(url,new DataReceiver(){

					@Override
					public void onReceice(byte[] s) {
						Bundle bundle = new Bundle();
				        bundle.putByteArray("data", s);
				        Message message = new Message();
				        message.what = DOWNLOAD_IMG;
				        message.setData(bundle);
				        handler.sendMessage(message);
						
					}}).start();  
                dialog.show();  
			}});
	}

	private Handler handler = new Handler() {  
		  
        @Override  
        public void handleMessage(Message msg) {  
        	Bundle bundle = msg.getData();
            byte[] data = bundle.getByteArray("data");  
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);  
            show.setImageBitmap(bitmap);  
            if(msg.what == DOWNLOAD_IMG){  
                dialog.dismiss();  
            }      
        };  
    };  
	
	private void init() {
		click = (Button)findViewById(R.id.click);
		show = (ImageView)findViewById(R.id.show);
		dialog = new ProgressDialog(this);  
        dialog.setTitle("提示");  
        dialog.setMessage("正在下载，请稍后...");  
        dialog.setCancelable(false);  
	}

	
}
